<template>
	<div>
        <pheader>
            <template slot="left">用户管理/用户配置</template>
            <div style="text-align: right;margin-right: 18px;" slot="right">
                <Button type="primary" size="small" @click="importStructs" v-if="this.$hasPerm('structImport')">组织序号</Button>
                <input type="file" id="file" @change="importFile" />
                <!-- <Button type="primary" size="small" @click="selectFile" v-if="this.$hasPerm('userImport')">批量导入</Button>
                <Button type="primary" size="small" @click="add()" v-if="this.$hasPerm('userAdd')">新增</Button> -->
                <Input v-model= "search_param" search placeholder="请输入用户账号或名称"  style="width: auto;" @on-search="search($event,0)"/>
            </div>
        </pheader>
        <div style="padding: 8px 8px 0px 8px;">
            <div style="width: 100%;background-color: white;height: calc(100vh - 108px);overflow-y: auto;padding:10px;">
                <Table border :columns="columns" :data="data" :loading="tableLoading" ref="table">
                    <template slot-scope="{ row, index }" slot="roles">
                            <span>{{showRoles(row.roles)}}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="tenants">
                        <span>{{showTenants(row.tenants)}}</span>
                    </template>
                     <template slot-scope="{ row, index }" slot="structs">
                        <span>{{showStructs(row.structs)}}</span>
                    </template>
                    <template slot-scope="{ row, index }" slot="action">
                        <div style="display: inline-block;">
                            <a v-if="$hasPerm('userEdit')" href="javascript:void(0)" @click="edit(index,row)">
                                <div class="text_link" style="width: 50px;">
                                    编辑
                                </div>
                            </a>
<!--                             <a v-if="$hasPerm('userMove')" href="javascript:void(0)" @click="deleteUser(row)">
                                <div class="text_link" style="width: 50px;">
                                    删除
                                </div>
                            </a> -->
<!--                             <a v-if="$hasPerm('userPassword')" href="javascript:void(0)" @click="editPassword(row)">
                                <div class="text_link" style="width: 80px;">
                                    重置密码
                                </div>
                            </a> -->
                        </div>
                    </template>
                </Table>
                <div style="margin: 10px;overflow: hidden">
                    <div style="float: right;">
                        <Page :current="page" :total="total" show-total show-elevator show-sizer @on-change="changePage" @on-page-size-change="changePageSize"></Page>
                    </div>
                </div>
                <Modal :mask-closable="false" @on-ok="add_ok()" @on-cancel="cancel('add_menu')"
                    v-model="add_menu.show" :loading="loading"
                    :title="!add_menu.isupdate?'新增用户':'编辑用户'" width="660">
                    <Form ref="add_menu" :model="add_menu" :rules="ruleInline" label-position="left" :label-width="100">
<!--                         <Row >
                            <Col span="10" >
                                <FormItem label="用户账号：" prop="user_number">
                                    <Poptip content="用户账号只能是字母、数字和下划线,且长度在5-20之间!">
                                        <Input v-model="add_menu.user_number" @on-change="checkNumber"/>
                                    </Poptip>
                                </FormItem>
                            </Col>
                            <Col span="10" style="left:10%">
                                <FormItem label="用户名称：" prop="user_name">
                                    <Input v-model="add_menu.user_name" />
                                </FormItem>
                            </Col>
                        </Row >
                        <Row >
                            <Col span="10">
                                <FormItem label="身份证号：" prop="id_card">
                                    <Input v-model="add_menu.id_card" @on-change="checkIdcard"/>
                                </FormItem>
                            </Col>
                            <Col span="10" style="left:10%">
                                <FormItem label="电话号码：" prop="phone">
                                    <Input v-model="add_menu.phone" @on-change="checkPhone"/>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row >
                            <Col span="10">
                                <FormItem label="个人邮箱:" prop="email">
                                    <Input v-model="add_menu.email" @on-change="checkEmail"/>
                                </FormItem>
                            </Col>
                            <Col span="10" style="left:10%" >
                                <FormItem label="4A账号:" >
                                    <Input v-model="add_menu.fourA"/>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row >
                          <Col span="10" >
                              <FormItem label="生效时间：" prop="effect_date">
                                  <DatePicker v-model="add_menu.effectDate" type="date"  placeholder="选择生效时间" format="yyyy-MM-dd" @on-change="changeEffectDate" :clearable="false"></DatePicker>
                              </FormItem>
                          </Col>
                          <Col span="10" style="left:10%">
                              <FormItem label="失效时间:" prop="expire_date">
                                  <DatePicker v-model="add_menu.expireDate" type="date"  placeholder="选择失效时间" format="yyyy-MM-dd" @on-change="changeExpireDate" :clearable="false"></DatePicker>
                              </FormItem>
                          </Col>
                        </Row>
                        <Row >
                            <Col span="10">
                                <FormItem label="账号状态:">
                                  <Select v-model="add_menu.status">
                                    <Option v-for="item in statusList" :value="item.value" :key="item.value">{{item.label}}</Option>
                                  </Select>
                                </FormItem>
                            </Col>
                            <Col span="10" style="left:10%" v-if="!add_menu.isupdate">
                                <FormItem label="账号密码:" prop="password">
                                    <Poptip content="密码以字母开头,长度在6-18之间,可以包含字母、数字和特殊符号!">
                                        <Input v-model="add_menu.password" type="password" password/>
                                    </Poptip>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row >
                          <Col span="23" >
                              <FormItem label="账号描述：" prop="des">
                                  <Input v-model="add_menu.des" type="textarea" :rows="3" style="width:97%"/>
                              </FormItem>
                          </Col>
                        </Row> -->
                        <Row style="padding:0 0 10px 0;color: #bbb;">
                            <span>
                                注：权限基于角色,请至少关联一个角色!</span>
                           <!-- <span>
                                注：权限基于角色,请至少关联一个角色!&nbsp;若用户需要关联项目,则需关联租户!</span> -->
                        </Row>
                        <Row>
                            <Col span="10" >
                                <FormItem label="关联角色：" :required="true">
                                    <Select :label-in-value="true" v-model="add_menu.roles" placeholder="搜索或下拉选择" filterable multiple style="width:500px">
                                        <Option v-for="item in roleList" :value="item.id" :key="item.id">{{item.role_name}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
<!--                         <Row>
                            <Col span="10" >
                                <FormItem label="关联租户：" >
                                    <Select :label-in-value="true" v-model="add_menu.tenants" placeholder="搜索或下拉选择" filterable multiple style="width:500px">
                                        <Option v-for="item in tenantList" :value="item.id" :key="item.id">{{item.tenant_name}}</Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row> -->
                        <Row>
                            <Col span="10">
                                <FormItem label="组织架构:" :required="true">
                                  <Select v-model="add_menu.structs" placeholder="搜索或下拉选择" filterable multiple style="width:500px">
                                      <Option v-for="item in structList" :value="item.id" :key="item.id">{{item.gName}}</Option>
                                  </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <!-- <Row >
                            <Col>
                                <FormItem label="用户头像：">
                                    <template>
                                    <div class="demo-upload-list" v-for="item in add_menu.imgList">
                                        <template v-if="item.status === 'finished'">
                                            <img :src="imageUrl + '/image/' + item.fileName">
                                            <div class="demo-upload-list-cover">
                                                <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                                                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                                            </div>
                                        </template>
                                        <template v-else>
                                            <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                                        </template>
                                    </div>
                                    <Upload
                                        :show-upload-list="false"
                                        :headers="httpHeader"
                                        :on-success="handleSuccess"
                                        :format="['jpg','jpeg','png']"
                                        type="drag"
                                        :action="imageUrl +'/image'"
                                        style="display: inline-block;width:58px;">
                                        <div style="width: 58px;height:58px;line-height: 58px;">
                                            <Icon type="ios-camera" size="20"></Icon>
                                        </div>
                                    </Upload>
                                    <Modal title="用户头像" v-model="visible">
                                        <img :src="imageUrl + '/image/' + add_menu.avatar" v-if="visible" style="width: 100%">
                                    </Modal>
                                    </template>
                                </FormItem>
                            </Col>
                        </Row> -->
                    </Form>
                </Modal>
                <Modal :mask-closable="false" @on-ok="okPassword" @on-cancel="cancel('pwdModal')" v-model="pwdModal.show" :loading="loading" title="重置密码" width="300">
                    <Form ref="pwdModal" :model="pwdModal" :rules="ruleInline" label-position="left" :label-width="100">
                        <Row>
                            <Col span="25">
                                <FormItem label="请输入密码:" prop="old_password">
                                    <Poptip content="密码以字母开头,长度在6-18之间,可以包含字母、数字和特殊符号!">
                                        <Input v-model="pwdModal.old_password" type="password" password/>
                                    </Poptip>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span="25">
                                <FormItem label="请再次输入密码:" prop="password">
                                    <Poptip content="密码以字母开头,长度在6-18之间,可以包含字母、数字和特殊符号!">
                                        <Input v-model="pwdModal.password" type="password" password/>
                                    </Poptip>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                <Modal v-model="showRepeatUser" @on-ok="showFileMould = false" title="批量导入用户" footer-hide>
                  <div style="position: relative;">
                    <p>导入成功数量：{{successUserLength}}</p>
                    <p>导入失败数量：{{repeatUserList.length}}</p>
                    <p v-if="repeatUserList.length > 0">以下为导入失败数据：</p>
                    <template v-if="repeatUserList != undefined && repeatUserList != null &&  repeatUserList.length > 0">
                      <List v-for="(item,index) in repeatUserList" :key="index">
                          <ListItem>
                            <ListItemMeta>
                              <template slot="title">
                                <p>账号名：{{item}}</p>
                              </template>
                            </ListItemMeta>
                          </ListItem>
                      </List>
                    </template>
                  </div>
                </Modal>
            </div>
        </div>
	</div>
</template>

<script>
    import untils from "../utils/excel";
    import expandRow from './user_expand.vue'
    import usermain from "./user_main"
    import mpage from "../comp_chatter/mpage"
    import pheader from "../comp_chatter/pheader"
    import mheader from "../comp_chatter/mheader"
    import mcontainer from "../comp_chatter/mcontainer"
    import Axios from 'axios'
    import ajax from "../ajax_util"
    import md5 from 'js-md5'

    export default {
        components: {expandRow, usermain, mpage, mheader, mcontainer,pheader},
        data () {
            const validateUser_number = (rule, value, callback) => {
                this.right.user_number_right=-1;
                this.repetition.user_number_repetition=-1;
                let reg = /^[A-Za-z0-9_]{5,20}$/;
                if(value === ''){
                    callback(new Error('请输入用户账号.'));
                }else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifNumber) ){
                    //console.log("----!!!----------",this.add_menu.isupdate,this.ifNumber);
                    if(!reg.test(value)){
                        this.right.user_number_right=1;
                        callback(new Error('用户账号格式不规范!'));
                    }
                    // else {
                    //     for(var i=0; i<this.user_numberList.length; i++){
                    //         if(value === this.user_numberList[i]){
                    //             this.repetition.user_number_repetition=1;
                    //             callback(new Error('该用户账号已存在!'));
                    //         }
                    //     }
                    //     callback();
                    // }
                    callback();
                }else{
                    callback();
                }
            };
            // const validateId_card = (rule, value, callback) => {
            //     this.repetition.id_card_repetition=-1;
            //     if(value === '') {
            //         callback(new Error('请输入身份证号.'));
            //     }else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifIdcard) ){
            //         for(var i=0; i<this.id_cardList.length; i++){
            //             if(value === this.id_cardList[i]){
            //                 this.repetition.id_card_repetition=1;
            //                 callback(new Error('该身份证号已被注册!'));
            //             }
            //         }
            //         callback();
            //     }else{
            //         callback();
            //     }
            // };
            // const validatePhone = (rule, value, callback) => {
            //     this.repetition.phone_repetition=-1;
            //     if(value === ''){
            //         callback(new Error('请输入电话号码.'));
            //     }else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifPhone) ){
            //         for(var i=0; i<this.phoneList.length; i++){
            //             if(value === this.phoneList[i]){
            //                 this.repetition.phone_repetition=1;
            //                 callback(new Error('该电话号码已被注册!'));
            //             }
            //         }
            //         callback();
            //     }else{
            //         callback();
            //     }
            // };
            // const validateEmail = (rule, value, callback) => {
            //     this.repetition.email_repetition=-1;
            //     if(value === ''){
            //         callback(new Error('请输入个人邮箱.'));
            //     }else if( (!this.add_menu.isupdate) || (this.add_menu.isupdate&&this.ifEmail) ){
            //         for(var i=0; i<this.emailList.length; i++){
            //             if(value === this.emailList[i]){
            //                 this.repetition.email_repetition=1;
            //                 callback(new Error('该邮箱已被注册!'));
            //             }
            //         }
            //         callback();
            //     }else{
            //         callback();
            //     }
            // };
            const validateId_card = (rule, value, callback) => {
                this.repetition.id_card_repetition=-1;
                let reg = this.validateUtils.idCardRule;
                if(value != '' && value != null) {
                    if(!reg.test(value)){
                        this.repetition.id_card_repetition=1;
                        callback(new Error('请输入正确的身份证号码!'));
                    }else{
                        callback();
                    }
                }else{
                    callback();
                }
            };
            const validatePhone = (rule, value, callback) => {
                this.repetition.phone_repetition=-1;
                let reg = this.validateUtils.telephoneRule;
                if(value != '' && value != null) {
                    if(!reg.test(value)){
                        this.repetition.phone_repetition=1;
                        callback(new Error('请输入正确的联系方式!'));
                    }else{
                        callback();
                    }
                }else{
                    callback();
                }
            };
            const validateEmail = (rule, value, callback) => {
                this.repetition.email_repetition=-1;
                let reg = this.validateUtils.eMailRule;
                if(value != '' && value != null) {
                    if(!reg.test(value)){
                        this.repetition.email_repetition=1;
                        callback(new Error('请输入正确的邮箱!'));
                    }else{
                        callback();
                    }
                }else{
                    callback();
                }
            };
            const validatePassword= (rule, value, callback) => {
                this.right.password_right=-1;
                let reg = /^[a-zA-Z][`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\w]{5,17}$/;
                if (value === '') {
                    callback(new Error('请输入账号密码!'));
                } else {
                    if(!reg.test(value)){
                        this.right.password_right=1;
                        callback(new Error('密码格式不规范!'));
                    }
                    callback();
                }
            };
            return {
                successUserLength: 0,   //批量导入成功用户数量
                repeatUserList: [],     //批量导出用户，重复的用户名
                showRepeatUser: false,  //显示批量导入错误的对话框
                tableLoading: false,
                deptInfo: "",
                deptList:[], //关联组织集合
                remoteLoading: false, // 组织搜索加载
                ruleInline: {
                    user_number: [
                         { required: true, validator: validateUser_number, trigger: 'blur' }
                    ],
                    user_name: [
                        { required: true, message: '请输入用户名称.', trigger: 'blur' }
                    ],
                    id_card:[
                        { required: false, validator: validateId_card, trigger: 'blur' }
                    ],
                    phone:[
                        { required: false, validator: validatePhone, trigger: 'blur' }
                    ],
                    email:[
                         { required: false, validator: validateEmail, trigger: 'blur' }
                    ],
                    old_password: [
                        { required: true, validator: validatePassword, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, validator: validatePassword, trigger: 'blur' }
                    ],
                    roles: [
                        { required: true, message: '请选择需要关联的角色.', trigger: 'blur' }
                    ]
                },
                imageUrl: this.CONFIG.file_url,
                add_menu:{
                  show:false,
                  user_number:"",
                  user_name:"",
                  phone:"",
                  roles:[],
                  //tenants:[],
                  structs:[],
                  avatar:"",
                  password:"",
                  email:"",
                  id_card:"",
                  fourA:"",
                  isupdate:false,
                  updateId:-1,
                  imgList:[],
                  effect_date:0,
                  effectDate:"",
                  expire_date:0,
                  expireDate:"",
                  des:"",
                  status:"1",
                  org_id:0
                },

                pwdModal:{
                  id:-1,
                  show:false,
                  user_number:"",
                  old_password:"",
                  password:""
                },

                loading: true,
                data: [],

                user_numberList:[],
                phoneList:[],
                emailList:[],
                repetition:{
                    user_number_repetition:-1,
                    phone_repetition:-1,
                    email_repetition:-1,
                    id_card_repetition:-1
                },
                right:{
                    user_number_right:-1,
                    password_right:-1
                },
                id_cardList:[],
                roleList: [],
                tenantList:[],
                total:0,

                page:1,
                pageSize:10,
                search_param:'',

                visible: false,
                httpHeader:  {
                    Authorization: this.$store.state.token
                },

                temp_number:"",
                temp_id_card:"",
                temp_phone:"",
                temp_email:"",
                ifNumber:false,
                ifIdcard:false,
                ifPhone:false,
                ifEmail:false,

                temp_roleId:[],
                structList:[],

                statusList:[
                    {
                        value:"1",
                        label:"正常"
                    },
                    {
                        value:"0",
                        label:"加锁"
                    }
                ]
            }
        },
        computed: {
            columns () {
                let columns = [];
                columns.push({
                    type: 'expand',
                    width: 50,
                    render: (h, params) => {
                        return h(expandRow, {
                            props: {
                                row: params.row,
                                roles: this.showRoles(params.row.roles),
                                tenants:this.showTenants(params.row.tenants)
                            }
                        })
                    }
                });
                columns.push({
                    title: '用户账号',
                    key: 'user_number',
                    width:'95px'
                });
                columns.push({
                    title: '用户名称',
                    key: 'user_name',
                    width:'100px'
                });
                columns.push({
                    title: '电话',
                    key: 'phone',
                    width:'150px'
                });
                // columns.push({
                //     title:'邮箱',
                //     key:'email',
                //     width:'150px'
                // });
                columns.push({
                    title: '关联的角色',
                    slot:'roles',
                    width:"200"
                });
                // columns.push({
                //     title: '关联的租户',
                //     slot:'tenants'
                // });
                columns.push({
                    title:'关联的组织',
                    //tooltip:true,
                    key:'structs',
                    slot: "structs",
                });
                if (this.$hasPerm('userEdit') || this.$hasPerm('userPassword') || this.$hasPerm('userMove')){
                    columns.push({
                        title: '操作',
                        key: 'action',
                        width: 100,
                        align: 'center',
                        slot: "action"
                    });
                }
                return columns;
            }
        },
        mounted() {
            //this.get_all_role();
            //this.search(this.search_param,0);
            this.search(this.search_param,0);
        },
        methods: {
            selectFile() {
              const el = document.getElementById("file");
              el.click();
            },
            async importFile() {
              this.tableLoading = true
              const el = document.getElementById("file");
              const file = el.files[0];
              var that = this
              var data = await untils.importFromLocal(file, 0);
              var columnsUser = [
                {
                    title: '账号名',
                    key: 'user_number',
                    align: 'center',
                },
                {
                    title: '用户姓名',
                    key: 'user_name',
                    align: 'center'
                },
                {
                    title: '电话号码',
                    key: 'phone',
                    align: 'center'
                },
                {
                    title: '身份证',
                    key: 'id_card',
                    align: 'center'
                },
                {
                    title: '4a账号',
                    key: 'fourA',
                    align: 'center'
                },
                {
                    title: '邮箱',
                    key: 'email',
                    align: 'center'
                },
                {
                    title: '组织架构',
                    key: 'structId',
                    align: 'center'
                }
              ]
              var temp = untils.handleInfoByColumns(data.body,columnsUser,that)
              this.setInUser(temp)
              console.log("data------------------->",temp)
              // this.title = data.title;
              // this.tableData = temp;
              el.value = "";
            },
            setInUser(userList){
              var that = this;
              var url = this.CONFIG.url_know+'/insertUsers';
              ajax.post({
                  url: url,
                  that: that,
                  data: userList,
                  success:function(data){
                    console.log("setInUser data--------->", data)
                    that.successUserLength = userList.length - data.length
                    that.repeatUserList = data
                    that.search(that.search_param,0);
                    that.showRepeatUser = true
                  }
              })
            },
            showRoles(roles){
                var str = "";
                for(var i=0; i<roles.length; i++){
                    if(roles[i].id>0){
                        str = str + roles[i].role_name + "、"
                    }
                }

                str = str.slice(0,str.length-1);
                return str;
            },
            showTenants(tenants){
                //console.log("=====",tenants);
                var str = "";
                for(var i=0; i<tenants.length; i++){
                    if(tenants[i].id>0){
                        str = str + tenants[i].tenant_name + "、"
                    }
                }

                str = str.slice(0,str.length-1);
                return str;
            },
            showStructs(structs){
                var str = "";
                for(var i=0; i<structs.length; i++){
                    if(structs[i].id>0){
                        str = str + structs[i].gName + "、"
                    }
                }

                str = str.slice(0,str.length-1);
                return str;
            },
            get_all_tenant(){
                var that=this;
                var url=this.CONFIG.url_know+'/listTenants';

                ajax.get({
                url:url,
                that:that,
                success:function(data){
                    //console.log("=========",data);
                    that.tenantList = data;
                }})
            },
            get_edit_roles(row){
                var u_id = this.$store.state.user.id;
                var that=this;
                var url=this.CONFIG.url_know+'/get-edit-roles/' + u_id;

                ajax.get({
                url:url,
                that:that,
                success:function(data){
                    console.log("=========",data);
                    that.roleList = data;
                    that.edit_user(row);
                }})
            },
            getStruct(){
                var that=this;
                var url=this.CONFIG.url_know+'/getAllStructs';
                ajax.get({
                url:url,
                that:that,
                success:function(data){
                    //console.log("=========",data);
                    that.structList = data;
                }})
            },
            search(param,number){
                this.tableLoading = true;

                if(param === undefined || param === null){
                    param = "";
                }
                if(number == 0){
                    this.page = 1;
                }

                this.search_param = param;
                var pageModel = {};
                pageModel.page = this.page;
                pageModel.pageSize = this.pageSize;
                pageModel.param = this.search_param;
                var that=this;
                var url=this.CONFIG.url_know+'/searchUsers';
                ajax.post({
                  url:url,
                  that:that,
                  data:pageModel,
                  success:function(data){
                    console.log("------data--------",data);
                    that.total = data.total;
                    that.data = data.userList;
                    that.tableLoading = false;
                }})
            },
            changePage (page) {
                this.page = page;
                this.search(this.search_param,1);
            },
            changePageSize(pageSize){
                this.pageSize = pageSize;
                this.search(this.search_param,0);
            },
            messageWarningFn (text) {
              this.$Message.warning(text)
              setTimeout(() => {
                this.loading = false
                this.$nextTick(() => {
                  this.loading = true
                });
              }, 1);
            },
            cancel(name){
                this.$refs[name].resetFields();
                // this.ifNumber = false;
                // this.ifIdcard = false;
                // this.ifPhone = false;
                // this.ifEmail = false;
                // this.right.user_number_right = -1;
                // this.repetition.user_number_repetition = -1;
                // this.repetition.id_card_repetition = -1;
                // this.repetition.phone_repetition = -1;
                // this.repetition.email_repetition = -1;
                // this.right.password_right = -1;
            },
            // checkNumber(){
            //     if(this.add_menu.user_number == this.temp_number){
            //         this.ifNumber = false;
            //     }else{
            //         this.ifNumber = true;
            //     }
            // },
            checkIdcard(){
                if(this.add_menu.id_card == this.temp_id_card){
                    this.ifIdcard = false;
                }else{
                    this.ifIdcard = true;
                }
            },
            checkPhone(){
                if(this.add_menu.phone == this.temp_phone){
                    this.ifPhone = false;
                }else{
                    this.ifPhone = true;
                }
            },
            checkEmail(){
                if(this.add_menu.email == this.temp_email){
                    this.ifEmail = false;
                }else{
                    this.ifEmail = true;
                }
            },
            add_ok(){
                // if (this.add_menu.user_number === '') {
                //     this.messageWarningFn('用户账号不能为空');
                //     return
                // }else if(this.right.user_number_right === 1){
                //     this.messageWarningFn('用户账号只能是字母和数字,且长度在5-20之间!');
                //     return
                // }
                // // else if(this.repetition.user_number_repetition === 1){
                // //     this.messageWarningFn('该用户账号已存在!');
                // //     return
                // // }
                // else if (this.add_menu.user_name === '') {
                //     this.messageWarningFn('用户名称不能为空');
                //     return
                // }else if(this.repetition.id_card_repetition === 1){
                //     this.messageWarningFn('请输入正确的身份证号码!');
                //     return
                // }else if(this.repetition.phone_repetition === 1){
                //     this.messageWarningFn('请输入正确的联系方式!');
                //     return
                // }else if(this.repetition.email_repetition === 1){
                //     this.messageWarningFn('请输入正确的邮箱!');
                //     return
                // }else if( this.add_menu.password === ''){
                //     this.messageWarningFn('账号密码不能为空');
                //     return
                // }else if( this.right.password_right === 1){
                //     this.messageWarningFn('密码以字母开头,长度在6-18之间,可以包含字母、数字和特殊符号!');
                //     return
                // }else
                var roleIdList = this.add_menu.roles.concat(this.temp_roleId);
                if( (roleIdList === undefined || roleIdList == null || roleIdList.length == 0) ){
                    this.messageWarningFn('请至少选择一个角色!');
                    return
                }else if( (this.add_menu.structs === undefined || this.add_menu.structs == null || this.add_menu.structs.length == 0) ){
                    this.messageWarningFn('请选择组织架构!');
                    return
                }else{
                    var that=this;
                    var url=this.CONFIG.url_know+'/user';
                    if(this.add_menu.isupdate){
                        var user={
                            // user_number:this.add_menu.user_number,
                            // user_name:this.add_menu.user_name,
                            // phone:this.add_menu.phone,
                            roleIdList:roleIdList,
                            //tenantIdList:this.add_menu.tenants,
                            structIdList:this.add_menu.structs,
                            // avatar:this.add_menu.avatar,
                            // email:this.add_menu.email,
                            // id_card:this.add_menu.id_card,
                            // fourA:this.add_menu.fourA,
                            // ifNumber:this.ifNumber,
                            // ifPhone:this.ifPhone,
                            // effect_date:this.add_menu.effect_date,
                            // expire_date:this.add_menu.expire_date,
                            // des:this.add_menu.des,
                            // status:this.add_menu.status,
                        };
                    }else{
                        var user={
                            // user_number:this.add_menu.user_number,
                            // user_name:this.add_menu.user_name,
                            // phone:this.add_menu.phone,
                            roleIdList:this.add_menu.roles,
                            //tenantIdList:this.add_menu.tenants,
                            structIdList:this.add_menu.structs,
                            // avatar:this.add_menu.avatar,
                            // password:md5(this.add_menu.password),
                            // email:this.add_menu.email,
                            // id_card:this.add_menu.id_card,
                            // fourA:this.add_menu.fourA,
                            // ifNumber:this.ifNumber,
                            // ifPhone:this.ifPhone,
                            // effect_date:this.add_menu.effect_date,
                            // expire_date:this.add_menu.expire_date,
                            // des:this.add_menu.des,
                            // status:this.add_menu.status,
                        };
                    }

                    // if(this.add_menu.structs != undefined && this.add_menu.structs != null && this.add_menu.structs.length>0){
                    //     user["org_id"] = this.add_menu.structs[0]
                    // }else{
                    //     user["org_id"] = 0;
                    // }

                    if(this.add_menu.isupdate){//说明是修改，不是新增
                        user["id"]=this.add_menu.updateId;
                        console.log("-------222------",this.add_menu,this.temp_roleId);
                        console.log("-------user------",user);
                        ajax.put({
                            url:url,
                            that:that,
                            data:user,
                            success:function(data){
                                if(data.code == 200){
                                    that.$Notice.success({
                                        title: '成功修改用户'
                                    });
                                    that.add_menu.show=false;
                                    // that.ifNumber = false;
                                    // that.ifIdcard = false;
                                    // that.ifPhone = false;
                                    // that.ifEmail = false;
                                    that.search(that.search_param,1);
                                }else{
                                    that.messageWarningFn(data.token);
                                }
                            }
                        })
                    }else{//说明是新增
                        //console.log("---------user-------",user);
                        ajax.post({
                            url:url,
                            that:that,
                            data:user,
                            success:function(data){
                                if(data == 0){
                                    that.messageWarningFn('该用户账号已存在!');
                                }else if(data == -1){
                                    that.messageWarningFn('该电话号码已注册!');
                                }else{
                                    that.$Notice.success({
                                    title: '成功新建用户'
                                    });
                                    that.add_menu.show=false;
                                    that.ifNumber = false;
                                    that.ifIdcard = false;
                                    that.ifPhone = false;
                                    that.ifEmail = false;
                                    that.search(that.search_param,0);
                                }
                            }
                        })
                    }
                }
            },
            add(){
                // if(this.tenantList.length<1){
                //     this.get_all_tenant();
                // }

                if(this.roleList.length<1){
                    this.get_edit_roles();
                }

                if(this.structList.length<1){
                    this.getStruct();
                }

                this.add_menu.isupdate=false;
                this.add_menu.show=true;
                this.add_menu.user_number="";
                this.add_menu.user_name="";
                this.add_menu.id_card="";
                this.add_menu.phone="";
                this.add_menu.email="";
                this.add_menu.password="a123456";
                this.add_menu.roles=[];
                //this.add_menu.tenants=[];
                this.add_menu.structs=[];
                this.add_menu.avatar="";
                this.add_menu.fourA="";
                this.add_menu.des = "";
                this.add_menu.status = "1";
                this.add_menu.org_id = 0;
                this.getYear();
                this.getNextYear();
            },
            edit(index,row){
                if(row.user_number=='admin' && !this.$hasPerm('admin')){
                    this.$Modal.warning({
                        title: '没有修改系统管理员的权限!',
                        width:'365'
                    });
                }else{
                    // if(this.tenantList.length<1){
                    //     this.get_all_tenant();
                    // }

                    if(this.structList.length<1){
                        this.getStruct();
                    }

                    if(this.roleList.length<1){
                        this.get_edit_roles(row);
                    }else{
                        this.edit_user(row)
                    }
                    // this.add_menu.isupdate=true;
                    // this.add_menu.updateId=row.id;
                    // this.add_menu.show=true;
                    // // this.add_menu.user_number=row.user_number;
                    // // this.add_menu.user_name=row.user_name;
                    // // this.add_menu.phone=row.phone;
                    // // this.add_menu.avatar=row.avatar;
                    // // this.add_menu.password=row.password;
                    // // this.add_menu.email=row.email;
                    // // this.add_menu.id_card=row.id_card;
                    // // this.add_menu.fourA=row.fourA;
                    // // this.add_menu.effect_date=row.effect_date;
                    // // this.add_menu.effectDate=this.formatDate(row.effect_date);
                    // // this.add_menu.expire_date=row.expire_date;
                    // // this.add_menu.expireDate=this.formatDate(row.expire_date);
                    // // this.add_menu.des=row.des;
                    // // this.add_menu.status=row.status;

                    // let roleList = [];
                    // for(var i=0; i<row.roles.length; i++){
                    //     roleList.push(row.roles[i].id);
                    // }
                    // // let tenantList = [];
                    // // for(var i=0; i<row.tenants.length; i++){
                    // //     tenantList.push(row.tenants[i].id);
                    // // }
                    // let structList = [];
                    // for(var i=0; i<row.structs.length; i++){
                    //     structList.push(row.structs[i].id);
                    // }
                    // this.add_menu.roles = roleList;
                    // //this.add_menu.tenants = tenantList;
                    // this.add_menu.structs = structList;

                    // let allEditRoleIdList = [];
                    // for(var i=0; i<this.roleList.length; i++){
                    //     allEditRoleIdList.push(this.roleList[i].id)
                    // }

                    // this.temp_roleId = [];
                    // console.log("00000000000");
                    // console.log(roleList,allEditRoleIdList);
                    // for(var i=0; i<roleList.length; i++){
                    //     //console.log("00000000000");
                    //     if(allEditRoleIdList.indexOf(roleList[i]) < 0){
                    //         //console.log("2222222");
                    //         this.temp_roleId.push(roleList[i]);
                    //     }
                    // }

                    // // this.temp_number = row.user_number;
                    // // this.temp_id_card = row.id_card;
                    // // this.temp_phone = row.phone;
                    // // this.temp_email = row.email;
                    // console.log(this.temp_roleId);
                }
            },
            edit_user(row){
                this.add_menu.isupdate=true;
                this.add_menu.updateId=row.id;
                this.add_menu.show=true;
                // this.add_menu.user_number=row.user_number;
                // this.add_menu.user_name=row.user_name;
                // this.add_menu.phone=row.phone;
                // this.add_menu.avatar=row.avatar;
                // this.add_menu.password=row.password;
                // this.add_menu.email=row.email;
                // this.add_menu.id_card=row.id_card;
                // this.add_menu.fourA=row.fourA;
                // this.add_menu.effect_date=row.effect_date;
                // this.add_menu.effectDate=this.formatDate(row.effect_date);
                // this.add_menu.expire_date=row.expire_date;
                // this.add_menu.expireDate=this.formatDate(row.expire_date);
                // this.add_menu.des=row.des;
                // this.add_menu.status=row.status;

                let roleList = [];
                for(var i=0; i<row.roles.length; i++){
                    roleList.push(row.roles[i].id);
                }
                // let tenantList = [];
                // for(var i=0; i<row.tenants.length; i++){
                //     tenantList.push(row.tenants[i].id);
                // }
                let structList = [];
                for(var i=0; i<row.structs.length; i++){
                    structList.push(row.structs[i].id);
                }
                this.add_menu.roles = roleList;
                //this.add_menu.tenants = tenantList;
                this.add_menu.structs = structList;

                let allEditRoleIdList = [];
                for(var i=0; i<this.roleList.length; i++){
                    allEditRoleIdList.push(this.roleList[i].id)
                }

                this.temp_roleId = [];
                console.log("00000000000");
                console.log(roleList,allEditRoleIdList);
                for(var i=0; i<roleList.length; i++){
                    //console.log("00000000000");
                    if(allEditRoleIdList.indexOf(roleList[i]) < 0){
                        //console.log("2222222");
                        this.temp_roleId.push(roleList[i]);
                    }
                }

                // this.temp_number = row.user_number;
                // this.temp_id_card = row.id_card;
                // this.temp_phone = row.phone;
                // this.temp_email = row.email;
                console.log(this.temp_roleId);
            },
            okPassword() {
                if(this.pwdModal.old_password === "" || this.pwdModal.password === ""){
                    this.messageWarningFn('请输入两次密码!');
                    return
                }else if( this.right.password_right === 1){
                    this.messageWarningFn('密码以字母开头,长度在6-18之间,可以包含字母、数字和特殊符号!');
                    return
                }else if(this.pwdModal.old_password != this.pwdModal.password){
                    this.messageWarningFn('两次密码不一致!');
                    return
                }else{
                    var that=this;
                    var url=this.CONFIG.url_know+'/password'
                    let user={
                      id:this.pwdModal.id,
                      user_number:this.pwdModal.user_number,
                      password:md5(this.pwdModal.password)
                    };
                    ajax.post({
                        url:url,
                        that:that,
                        data:user,
                        success:function(data){
                            that.search(that.search_param,0);
                            that.$Notice.success({
                            title: '成功重置密码!'
                            });
                        }
                    })
                    this.pwdModal.show=false;
                }
            },
            editPassword(row){
                if(row.user_number=='admin' && !this.$hasPerm('admin')){
                    this.$Modal.warning({
                        title: '没有修改系统管理员的权限!',
                        width:'365'
                    });
                }else{
                    this.pwdModal.id=row.id;
                    this.pwdModal.show=true;
                    this.pwdModal.user_number=row.user_number;
                    this.pwdModal.old_password="";
                    this.pwdModal.password="";
                }
            },
            deleteUser(row){
                if(row.user_number == "admin"){
                    this.$Modal.warning({
                        title: '不能删除系统管理员账号!',
                        width:'365'
                    });
                }else{
                    this.$Modal.confirm({
                        title:'确定删除该用户？',
                        width:'360',
                        onOk:() => {
                            this.del(row.id)
                        }
                    });
                }
            },
            del(id) {
                var that=this;
                var url=this.CONFIG.url_know+'/user/'+id;
                ajax.del({
                  url:url,
                  that:that,
                  success:function(){
                    if(that.data.length === 1 && that.page > 1){
                        that.page = that.page-1;
                    }
                    that.search(that.search_param,1);
                    that.$Notice.success({
                      title: '成功删除用户'
                    });
                  }
                });
            },
            formatDate(date){
              return this.utils.formatDate(new Date(date*1000), "yyyy-MM-dd")
            },
            changeEffectDate(date){
                this.add_menu.effectDate = date;
                var time = new Date(date);
                this.add_menu.effect_date = (time.getTime() / 1000);
            },
            changeExpireDate(date){
                this.add_menu.expireDate = date;
                var time = new Date(date);
                this.add_menu.expire_date = (time.getTime() / 1000);
                //console.log("=====changeExpireDate=======",time,this.add_menu.expire_date);
            },
            getYear(){
              var now = Date.now();
              var date = this.utils.formatDate(new Date(now), "yyyy-MM-dd");
              this.changeEffectDate(date);
              //return date;
            },
            getNextYear(){
              var now = Date.now();
              var temp = new Date(now);
              var nextYear = temp.getFullYear() + 1;
              var month = temp.getMonth()+1;
              var day = temp.getDate();
              var date = nextYear+"-"+month+"-"+day;
              this.changeExpireDate(date);
              //return date;
            },
            handleView (name) {
                this.imgName = name;
                this.visible = true;
            },
            handleRemove (file) {
                this.add_menu.imgList.some((item, index) => {
                    if(item.name === file.name){
                        this.add_menu.imgList.splice(index,1);
                        return true;
                    }
                });
            },
            handleSuccess (response, file, fileList) {
                //console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!");
                //console.log(file.name);
                this.add_menu.imgList.push({
                    fileUrl: response,
                    fileName:  file.name
                })
                fileList = []
                this.add_menu.avatar = file.name;
                this.$Notice.success({
                    title: '成功上传头像!'
                });
            },

            importStructs(){
                var columns = [
                    {
                        "title": "序号",
                        "key": "id",
                    },
                    {
                        "title": "组织名称",
                        "key": "gName",
                    }
                ];
                var that=this;
                var url=this.CONFIG.url_know+'/getStructList';
                ajax.get({
                  url:url,
                  that:that,
                  success:function(data){
                    //console.log("==============",data);
                    that.$refs.table.exportCsv({
                        filename: '组织架构列表',
                        columns:columns,
                        data:data
                    });
                  }
                });
            }
        }
    }
</script>

<style lang="scss">
    @import "../utils/base.scss";
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
	#file {
	  display: none;
	}
    td.ivu-table-expanded-cell {
      padding: 0px;
    }
</style>
